// common variable
var common = require('./common');

// auto define common variable
var evalString = '';
Object.keys(common).forEach((e,i) => {
    evalString += `var ${e} = common.${e};`;
});
if(typeof(evalString) !== 'undefined' || evalString !== null){
    eval(evalString);
}

describe("test register and login", function () {
    var LoginToken;
    var token;
    var userID;
    before(function (done) {
        request
            .post(host + "/api/register")
            .send({
                mobile: "18340861701",
                password: "Bln12345",
                userName: "bian",
                avatar: "www.baidu.com"
            }).end(function (err, res) {
            try {
                var data = JSON.parse(res.text);
            } catch (e) {
                console.log(err);
            }
            data.status.should.be.exactly(true);
            token = data.msg.token;
            LoginToken = data.msg.LoginToken;
            userID = data.msg.userID;
            done();
        });
    });

    beforeEach(function (done) {
        request
            .post(host + "/api/login")
            .send({
                mobile: "18340861701",
                password: "Bln12345"
            }).end(function (err, res) {
            try {
                var data = JSON.parse(res.text);
            } catch (e) {
                console.log(err);
            }
            data.status.should.be.exactly(true);
            token = data.msg.token;
            LoginToken = data.msg.LoginToken;
            userID = data.msg.userID;
            done();
        });
    });

    it("cache should work ok", function (done) {
        cache._client.getAsync(LoginToken).then(function (res) {
            var data = JSON.parse(res);
            data.mobile.should.be.exactly("18340861701");
            data.password.should.be.exactly("Bln12345");
            var str = data.mobile + data.password;
            token.should.be.exactly(utilx.getToken(str));
            data.id.should.be.exactly(userID);
            done();
        });
    });

    it("get a new LoginToken should be ok", function (done) {
        request
            .post(host + "/api/getToken")
            .send({token: token})
            .end(function (err, res) {
                try {
                    var data = JSON.parse(res.text);
                } catch (e) {
                    console.log(err);
                }
                data.status.should.be.exactly(true);
                data.msg.userID.should.be.exactly(userID);
                LoginToken = data.msg.LoginToken;
                done();
            });
    });

    after(function (done) {
        db.models.User.destroy({
            where: {
                mobile: "18340861701"
            }
        }).then(function () {
            done();
        });
    });
});

